//
//  CZPictureBrowerCell.swift
//  weibo27
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

//通知代理做事情
protocol PictureBrowerCellDelegate:NSObjectProtocol{
    
    func pictureBrowerCellDidTapImage()
}


class CZPictureBrowerCell: UICollectionViewCell {

    
    weak var pictureBrowerCellDelegate:PictureBrowerCellDelegate?
    
    
    //添加一个target事件  UIScrollView是对touchesBegan的一个封装，是不能直接使用touchesBegan的
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //touchesBegan是一个底层功能，已经被手势给高度封装了
    }
    
    @objc private func tapImage(){
        print("cell被点击了")
        //通知代理做事情
        pictureBrowerCellDelegate?.pictureBrowerCellDidTapImage()
    }
    
    
    //图片的地址
    var imageUrl : NSURL? {
        
        didSet{
            
            setOriginalScrollViewContent()
            
            guard let url = imageUrl else{
                return
            }
            
            // 1 ulr 缩略图的地址  从本地磁盘加载
            let placeHolderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString)
            
            setPlaceHodler(placeHolderImage)
//            imageView.image = placeHolder
//            //设置大小
//            imageView.sizeToFit()
//            // 设置中心
//            imageView.center = scrollView.center
            
            imageView.sd_setImageWithURL(bmiddleUrl(url), placeholderImage: nil, options: [SDWebImageOptions.RefreshCached,SDWebImageOptions.RetryFailed], progress: { (current, total) -> Void in
                
//                   print("current = \(current) + total = \(total)")
                
                  dispatch_async(dispatch_get_main_queue()) { () -> Void in
                    self.placeHolder.progress = CGFloat(current / total )
                  }
                
                }) { (image, _, _, _) -> Void in
                
                    if image==nil{
                        SVProgressHUD.showInfoWithStatus("您的网络不给力，请稍后再试")
                    }
                    
                //隐藏占位图片
                self.placeHolder.hidden = true
                //sd_Web有一个功能，一旦设置了通过url异步加载，就会清除之前的图片/如果之前下载，但是没有完成，就取消
                self.imageView.center = CGPointZero
                
                //设置图片的位置
                self.setPosition(image)
                
            }

            
        }
    }
    
    //设置占位图像
    private func setPlaceHodler(image:UIImage?){
        placeHolder.hidden = false
        
        placeHolder.image = image
        placeHolder.center = scrollView.center
        placeHolder.sizeToFit()
    }
    
    
    /// 设置图片的具体位置
    private func setPosition(image:UIImage){
        let size = self.displaySize(image)
        
        //如果图片的高度小于scrollView的高度
        if size.height<scrollView.bounds.size.height{
            
            self.imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            let y = (self.scrollView.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }else{
            self.imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            scrollView.contentSize = size
        }
        
        //如果图片过高，进行显示处理
    }
    
    /// 将ScrollView的各种操作限制都给清除掉，因为cell的重用问题
    private func setOriginalScrollViewContent(){
        
        //将图片的缩放比例清理
        imageView.transform = CGAffineTransformIdentity
        
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    /// 根据scrollview的宽高计算图片的尺寸
    private func displaySize(image:UIImage)->CGSize{
        
        let w = scrollView.bounds.width
        
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    }
    
    // 替换小图的地址
    private func bmiddleUrl(url:NSURL)-> NSURL{
        
        var urlString = url.absoluteString
        
        //替换指定的字符串
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/large/")
        
        return NSURL(string: urlString)!
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    lazy var scrollView:UIScrollView = UIScrollView()
    
    lazy var imageView:UIImageView = UIImageView()
    
    //占位图像
    private lazy var placeHolder : CZProgressImage = CZProgressImage()
    
    private func setupUI(){
        
        addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(placeHolder)
        //设置frame
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        
        //进行缩放操作
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.2
        scrollView.maximumZoomScale = 2.0
        
        //4 添加一个手势
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
}

extension CZPictureBrowerCell:UIScrollViewDelegate{
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imageView
    }
    
    /// 这个函数是在完成缩放之后调用 view 是返回缩放的视图
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        print("\(view)+\(view?.frame)")
        
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        
         offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        
        offsetX = offsetX < 0 ? 0 : offsetX
        
        //设置frame
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
 
    
}








